 

package com.zdkj.auth.handler;

import com.zdkj.admin.api.entity.SysLog;
import com.zdkj.common.core.constant.CacheConstants;
import com.zdkj.common.core.constant.CommonConstants;
import com.zdkj.common.log.event.SysLogEvent;
import com.zdkj.common.log.util.SysLogUtils;
import com.zdkj.common.security.handler.AbstractAuthenticationSuccessEventHandler;
import com.zdkj.common.security.service.PigxUser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.Cache;
import org.springframework.cache.CacheManager;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Optional;

/**
 * 权限认证成功处理
 * @author cui_com
 * @date 2018/10/8
 */
@Slf4j
@Component
public class PigxAuthenticationSuccessEventHandler extends AbstractAuthenticationSuccessEventHandler {

	@Autowired
	private CacheManager cacheManager;

	@Autowired
	private ApplicationEventPublisher publisher;

	/**
	 * 处理登录成功方法
	 * <p>
	 * 获取到登录的authentication 对象
	 *
	 * @param authentication 登录对象
	 * @param request        请求
	 * @param response       返回
	 */
	@Override
	public void handle(Authentication authentication, HttpServletRequest request, HttpServletResponse response) {
		log.info("用户：{} 登录成功", authentication.getPrincipal());
		PigxUser user = (PigxUser) authentication.getPrincipal();
		Cache failCountCache = cacheManager.getCache(CacheConstants.LOGIN_FAIL_COUNT);
		if(failCountCache != null && failCountCache.get(user.getUsername()) != null){
			failCountCache.evict(user.getUsername());
		}
		//save log
		SysLog sysLog = SysLogUtils.getLoginLog(authentication);
		sysLog.setType(CommonConstants.LOG_TYPE_SUCCESS);
		//登录成功，记录用户工号，用户名称，部门名称 线路编号（如果有），线路名称， 车站编号（如果有），车站名称
		sysLog.setCreateByName(user.getNikeName());
		sysLog.setCreateByLineCode(Optional.ofNullable(user.getLineCode()).orElse(""));
		sysLog.setCreateByStationCode(Optional.ofNullable(user.getStationCode()).orElse(""));
		sysLog.setCreateByDeptId(user.getDeptId());
        publisher.publishEvent(new SysLogEvent(sysLog));
	}
}
